// src/components/AsyncButton.tsx
import { Button, ButtonProps } from 'antd';
import React, { useState, useEffect } from 'react';

interface AsyncButtonProps extends ButtonProps {
  onClick?: (e: any) => Promise<void> | void;
  debounce?: number; // 防抖时间（毫秒）
}

const AsyncButton: React.FC<AsyncButtonProps> = ({
  onClick,
  debounce = 300,
  children,
  ...rest
}) => {
  const [loading, setLoading] = useState(false);
  const [isPending, setIsPending] = useState(false);

  const handleClick = async (e: React.MouseEvent) => {
    if (loading || isPending) return;

    setIsPending(true);
    setLoading(true);

    try {
      await onClick?.(e);
    } finally {
      // 防抖延迟后重置状态
      setTimeout(() => {
        setLoading(false);
        setIsPending(false);
      }, debounce);
    }
  };

  // 组件卸载时清除可能的定时器（安全措施）
  useEffect(() => {
    return () => {
      setIsPending(false);
      setLoading(false);
    };
  }, []);

  return (
    <Button {...rest} loading={loading} onClick={handleClick}>
      {children}
    </Button>
  );
};

export default AsyncButton;
